package com.monkey.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.monkey.dao.dos.Archives;
import com.monkey.dao.mapper.ArticleBodyMapper;
import com.monkey.dao.mapper.ArticleMapper;
import com.monkey.dao.mapper.ArticleTagMapper;
import com.monkey.dao.pojo.Article;
import com.monkey.dao.pojo.ArticleBody;
import com.monkey.dao.pojo.ArticleTag;
import com.monkey.dao.pojo.SysUser;
import com.monkey.service.*;
import com.monkey.utils.UserThreadLocal;
import com.monkey.vo.ArticleBodyVo;
import com.monkey.vo.Results;
import com.monkey.vo.TagsVo;
import com.monkey.vo.params.ArticleParam;
import com.monkey.vo.params.PageParams;
import com.monkey.vo.ArticleVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：monkey-L
 * @description: .
 * @date: 11:04 2021/10/4
 */
@SuppressWarnings({"all"})
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleTagMapper articleTagMapper;

//    @Override
//    public Results listArticles(PageParams pageParams) {
//        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
//        IPage<Article> articleIPage = this.articleMapper.listArticle(page,pageParams.getCategoryId(),pageParams.getTagId(),pageParams.getYear(),pageParams.getMonth());
//        return Results.success(copyList(articleIPage.getRecords(),true,true));
//    }
    @Override
    public Results listArticles(PageParams pageParams) {
        /*
         *功能描述: 分页查询数据库， article数据库表
         * @author monkey-L
         * @date
         * @param
         * @return
         */
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        if (pageParams.getCategoryId() != null) {
            // and category_id = #{categoryId}
            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
        }

        List<Long> articleIdList  = new ArrayList<>();
        if (pageParams.getTagId() != null) {
            //加入标签条件查询
            //article表中并没有tag字段，一篇文章有多个标签
            //article_tag 表进行关联，article_id 和 tag_id
            LambdaQueryWrapper<ArticleTag> articleTagQueryWrapper = new LambdaQueryWrapper<>();
            articleTagQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagQueryWrapper);
            for (ArticleTag articleTag : articleTags) {
                articleIdList.add(articleTag.getArticleId());
            }
            if (articleIdList.size() > 0) {
                //and id in (articleIdList中的值)
                queryWrapper.in(Article::getId, articleIdList);
            }
        }
        //根据文章发布时间逆序排序
        //是否置顶排序
        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
//        queryWrapper.orderByDesc()
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();
//        System.out.println("==============");
//        for (Article record : records) {
//            System.out.println(record);
//        }
//        System.out.println("==============");

        //此时不能直接返回，我们需要的是基于页面的vo，而不是直接的数据库的pojo
        List<ArticleVo> articleVoList = copyList(records, true, true);
        return Results.success(articleVoList);
    }

    @Override
    public Results hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Results.success(copyList(articles,false, false));
    }

    @Override
    public Results newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Results.success(copyList(articles,false, false));
    }

    @Override
    public Results listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Results.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    @Override
    public Results findArticleById(Long id) {
        /*
         *功能描述:
         * @author monkey-L
         * 1.根据id查询文章信息
         * 2.根据bodyId和categoryId去做关联查询
         * @return
         */
        Article article = articleMapper.selectById(id);
        ArticleVo articleVo = copy(article, true, true, true, true);
        //查看文章，增加阅读数，有没有问题呢
        //查看文章之后，本应该直接返回数据了，这时候做了一个更新的操作，更新时加写锁，阻塞
        //其他的读操作，性能就会比较低
        //更新增加了此次接口的耗时，如果一旦更新出问题，不能影响看文章的操作
        //线程池来解决，可以把更新操作扔到线程池中去执行，和主线程就不相关了
        threadService.updateViewCount(articleMapper,article);
        return Results.success(articleVo);
    }

    @Override
    public Results publish(ArticleParam articleParam) {
        /*
         *功能描述:
         * @author monkey-L
         * 1.发布文章，目的是构建Article对象
         * 2.作者id，当前登录的用户获取
         * 3.标签，要将标签加入到关联列表当中
         * 4.body内容存储 article bodyId
         * @return
         */
        //此接口要加入到登录拦截当中
        SysUser sysUser = UserThreadLocal.get();
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setCreateDate(System.currentTimeMillis());
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setBodyId(-1L);
        //插入之后会生成一个文章id
        articleMapper.insert(article);
        //tag
        List<TagsVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagsVo tag : tags) {
                Long id = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(id);
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
//        Map<String, String> map = new HashMap<>();
//        map.put("id", article.getId().toString());
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        return Results.success(articleVo);
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVos = new ArrayList<>();
        for (Article record : records) {
            articleVos.add(copy(record, isTag, isAuthor,false,false));
        }
        return articleVos;
    }
    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        List<ArticleVo> articleVos = new ArrayList<>();
        for (Article record : records) {
            articleVos.add(copy(record, isTag, isAuthor,isBody,isCategory));
        }
        return articleVos;
    }
    @Autowired
    private CategoryService categoryService;

    private ArticleVo copy(Article art, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory){
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(art.getId()));
        //此方法是spring提供的对相应属性的类进行拷贝
        BeanUtils.copyProperties(art,articleVo);
        articleVo.setCreateDate(new DateTime(art.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));
        if (isTag) {
            Long articleId = art.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = art.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = art.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        if (isCategory) {
            Long categoryId = art.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
